#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import yaml

class Config:
    """应用配置类，用于加载和管理配置"""
    
    def __init__(self):
        self.config_data = {}
        self.load_config()
    
    def load_config(self):
        """加载配置文件"""
        try:
            config_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'application.yml')
            
            if not os.path.exists(config_file):
                print(f"配置文件不存在: {config_file}，将使用默认配置")
                return
            
            with open(config_file, 'r', encoding='utf-8') as f:
                self.config_data = yaml.safe_load(f)
                print(f"成功加载配置文件: {config_file}")
        except Exception as e:
            print(f"加载配置文件时出错: {e}")
    
    def get(self, key, default=None):
        """
        获取配置项，支持点号分隔的路径
        例如：config.get('logging.level') 将返回 self.config_data['logging']['level']
        """
        if not key:
            return default
        
        try:
            parts = key.split('.')
            value = self.config_data
            
            for part in parts:
                value = value.get(part, {})
            
            # 如果找到了空字典 {}，但原始配置中没有该键，则返回默认值
            if value == {} and parts[-1] not in self.config_data.get(parts[0], {}):
                return default
            
            return value
        except (KeyError, AttributeError):
            return default
    
    def __getitem__(self, key):
        """允许使用 config['key'] 语法访问配置"""
        return self.get(key)
    
    def reload(self):
        """重新加载配置文件"""
        self.config_data = {}
        self.load_config()
        return self.config_data

# 创建全局配置实例
config = Config()
